import React from "react";
import styles from "./index.less";
import { Table, Card, Row, Col, Input, Button, Divider, Drawer,message,Steps,Modal,Tree ,Select,Tag,Collapse  } from "antd";
import Link from "umi/link";

import { fetchList,deleteUser,addUser} from "@/services/userCenter";
import { loadUnAssignTask,assignTask } from "@/services/taskCenter"
import WrappedUserAddForm from "@/pages/UserCenter/add/component/UserAddForm";
const { Option, OptGroup } = Select;
const { Step } = Steps;
const { TreeNode } = Tree;
const { Search } = Input;
const { Panel } = Collapse;

const DescriptionItem = ({ title, content }) => (
  <div
    style={{
      fontSize: 14,
      lineHeight: '22px',
      marginBottom: 7,
      color: 'rgba(0,0,0,0.65)',
    }}
  >
    <p
      style={{
        marginRight: 8,
        display: 'inline-block',
        color: 'rgba(0,0,0,0.85)',
      }}
    >
      {title}:
    </p>
    {content}
  </div>
);
const pStyle = {
  fontSize: 16,
  color: 'rgba(0,0,0,0.85)',
  lineHeight: '24px',
  display: 'block',
  marginBottom: 16,
};

class App extends React.Component {
  state = {
    data: [],
    pagination: {},
    loading: false,
    // 搜索相关参数
    searchCondition: {},
    visible: false,
    editVisible:false,
    addVisible:false,
    addModalKey:0,
    del_id:0
  };

  constructor(props) {
    super(props);

    // const {query} = props.location;
    // const { history } = props;
    // const pagination = {
    //   current:parseInt(query.page)?parseInt(query.page):1
    // }
    
    this.setState({
      pageNumber: parseInt(window.location.hash.slice(1), 0) || 1,
      collapseVisible:false

    })
    this.onKeyChange = this.onKeyChange.bind(this);
    this.handleSearch = this.handleSearch.bind(this);
    this.refresh = this.refresh.bind(this);
    this.showModal = this.showModal.bind(this);


    this.columns = [
      {
        title: "#",
        render: (text, record, index) =>{
          return (<span>{index+1}</span>)
        }
      },
      {
        title: "姓名",
        dataIndex: "userName",
      },
      {
        title: "账号",
        dataIndex: "account",
      },
      {
        title: "部门",
        dataIndex: "department.departmentName",
      },
      {
        title: "状态",
        dataIndex: "status",
        render:(text,record)=>(
          <div> 
          {
          text == 1 ? (<Tag color="#f50">忙碌</Tag>) : (<Tag color="#87d068">空闲</Tag>)
          }
          </div>
        )
      },
      {
        title: "操作",
        key: "actions",
        width:300,
        render: (text, record) => (
          <div>
            <Link onClick={()=>this.showTaskModal(record.id)}>分配任务</Link>
            <Divider type="vertical" />
            <Link onClick={()=>this.showCollapseModal(record.id)}>已分配任务</Link>
            <Divider type="vertical" />
            <Link onClick={()=>this.showEditModal(record.id)}>编辑</Link>
            <Divider type="vertical" />
            <Link onClick={()=>this.showModal(record.id)}>删除</Link>
          </div>
        )
      }
    ];
  }

  componentDidMount() {
    this.fetch().catch(res => {
      console.error(res);
    });
  }

  refresh() {
    this.handleTableChange(this.state.pagination);
  }

  fetch = async (params = {}) => {
    this.setState({ loading: true });
    const type = window.location.href.split('user/')[1];
    params.type = type
    const response = await fetchList(params);
    const pagination = { ...this.state.pagination };
    if (response.meta) {
      pagination.total = response.meta.total;
      pagination.pageSize = response.meta.per_page;
    }
    
    this.setState({
      data: response.data,
      loading: false,
      pagination
    });

    
  };

  // 列表翻页
  handleTableChange = pagination => {
    const { pager = pagination, searchCondition = {} } = this.state;
    pager.current = pagination.current;
    this.setState({
      pageNumber: pagination.current,
      pagination: pager
    }),()=>{
      window.location.hash = `#${pagination.current}`;
    }
    this.fetch({
      page: pagination.current,
      ...searchCondition
    });
  };

  // 搜索函数
  handleSearch() {
    const { title, pagination } = this.state;
    // 重置页码
    const pager = { ...pagination };
    pager.current = 1;
    this.setState(
      {
        pagination: pager,
        searchCondition: {
          keyword: title,
        }
      },
      function() {
        // 设置完条件后进行请求
        const { searchCondition } = this.state;
        this.fetch({
          ...searchCondition
        });
      }
    );
  }

  // 查询条件中的姓名改动监听
  onKeyChange(e) {
    this.setState({
      title: e.target.value
    });
  }

  handleChange = (e) => {

    this.setState({
      stageSelected:e
    })
  }

  handleShowChange = (e) => {

    this.setState({
      showSelected:e
    })
  }

  showTaskModal = async (e) => {
    const taskResponse = await loadUnAssignTask()
    
    this.setState({
      taskVisible: true,
      taskTree:taskResponse,
      personId:e
    });
  }

  showCollapseModal = async(e) => {
    this.setState({
      collapseVisible:true,
      personId:e
    })
  }

  handleCollapseCancel = () => {
    this.setState({
      collapseVisible:false,
    })
  }

  handleTaskCancel = () => {
    this.setState({
      taskVisible: false,
    });
  }

  showModal = (id) => {
    this.setState({
      visible: true,
    });

    this.setState({
      del_id: id,
    });
  };

  // 删除
  handleOk = e => {
    this.setState({
      visible: false,
    });
    const id = this.state.del_id

    deleteUser(id).then(res => {
      this.refresh()
      message.success('删除成功');
    });

  };

  handleCancel = e => {
    this.setState({
      visible: false,
      del_id:0
    });
  };

  onBlurSort = (e,id) => {
    const param = {
      id:id,
      sort:this.state.sort
    }
    addUser(param).then(res => {
      this.refresh()
    })
  };
  changeSort = (e,id) =>{
    this.setState({
      sort:e
    })
  }

  // 编辑
  showEditModal = (id) =>{
    this.setState({
      addModalKey: this.state.addModalKey + 1,
      editVisible: true,
      edit_id:id
    });
  }

  handleEditCancel = e => {
    this.setState({
      editVisible: false,
      edit_id:0
    });
  }

  // 添加
  showAddModal = e =>{
    this.setState({
      addModalKey: this.state.addModalKey+1,
      addVisible: true,
    });
  }

  handleAddCancel =e =>{
    this.setState({
      addVisible: false,
      editVisible: false,
    });
  }

  refresh1 = e =>{
    this.handleTableChange(this.state.pagination);
  }

  onExpand = expandedKeys => {
    console.log('onExpand', expandedKeys);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  onCheck = checkedKeys => {
    console.log('onCheck', checkedKeys);
    this.setState({ checkedKeys });
  };

  onSelect = (selectedKeys, info) => {
    console.log('onSelect', info);
    this.setState({ selectedKeys });
  };

  handleAssignOk = async () => {
    let checkedKeys = this.state.checkedKeys

    let assignTaskKeys = []
    checkedKeys && checkedKeys.map((item)=>{
      if(item.indexOf('child') >= 0){
        let taskKey = item.split('_')[1]
        assignTaskKeys.push(taskKey)
      }
    })

    await assignTask({taskIds:assignTaskKeys,personId:this.state.personId})
  }

  renderTreeNodes  =  (data) =>{

    data && data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
    return <TreeNode {...item} />;
  });
}

onChange = e => {
  const { value } = e.target;
  const expandedKeys = this.state.taskTree
    .map(item => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, gData);
      }
      return null;
    })
    .filter((item, i, self) => item && self.indexOf(item) === i);
  this.setState({
    expandedKeys,
    searchValue: value,
    autoExpandParent: true,
  });
};
  

  render() {
    const { title , taskTree} = this.state;
    const type = window.location.href.split('user/')[1];

    function filter(inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    }

    return (
      <Row gutter={[16, 16]}>
        {/* 检索条件部分 */}
        <Col>
          <Card title="筛选查询">
            <Row gutter={16}>
              <Col span={4}>
                <div className={styles.inputGroup}>
                  <span className={styles.label}>标题:</span>
                  <Input
                    defaultValue={title}
                    onPressEnter={this.handleSearch}
                    value={title}
                    onChange={this.onKeyChange}
                    className={styles.input}
                  />
                </div>
              </Col>
              

              {/*  搜索动作 */}
              <Col span={4}>
                <Button icon="search"  type="primary" onClick={this.handleSearch}>
                  搜索
                </Button>
              </Col>
            </Row>
          </Card>
        </Col>
        {/* 数据展示部分 */}
        <Col>
          <Card
            title="数据列表"
            // extra={<Button icon="plus-circle" type="primary" href={`/admin/user/add`}>添加</Button>}
            extra={<Button icon="plus-circle" type="primary" onClick={this.showAddModal}>添加</Button>}
          >
            
            <Table
              columns={this.columns}
              rowKey={record => record.id}
              dataSource={this.state.data}
              pagination={this.state.pagination}
              loading={this.state.loading}
              onChange={this.handleTableChange}
            />
          </Card>
          <Modal
            title="分配任务"
            visible={this.state.taskVisible}
            onOk={this.handleAssignOk}
            onCancel={this.handleTaskCancel}
            key={"assign"}
          >
            <Col>

            <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={this.onChange} />            
              <Tree
                checkable
                onSelect={this.onSelect}
                onCheck={this.onCheck}
                onExpand={this.onExpand}
                expandedKeys={this.state.expandedKeys}
                autoExpandParent={this.state.autoExpandParent}
              >
                {taskTree&&taskTree.map(item=>{
                    return (<TreeNode title={item.title} key={item.key} value={item.value}>
                      {item.children && item.children.map(node=>{
                        return <TreeNode title={node.title} key={node.key} value={node.value}/>
                      })}
                      </TreeNode>)
                  })}
              </Tree>
            </Col>
            
          </Modal>

          <Modal
            title="温馨提示"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            key={'tip'}
          >
            <p>数据删除后不可恢复，您确定要删除此条数据吗？</p>
          </Modal>

          <Modal
            title={type == 1 ? '编辑企业新闻' : '编辑行业新闻'}
            visible={this.state.editVisible}
            onCancel={this.handleEditCancel}
            footer={[]}
            width={900}
            key={this.state.addModalKey}
            height={800}
            style={{overuserY:'auto',overuserX:'hidden'}}
          >
            {this.state.edit_id ? <WrappedUserAddForm id={this.state.edit_id} handleAddCancel={this.handleAddCancel} refresh={this.refresh1} /> : null}
          </Modal>

          <Modal
            title={type == 1 ? '添加企业新闻' : '添加行业新闻'}
            visible={this.state.addVisible}
            onCancel={this.handleAddCancel}
            footer={[]}
            width={900}
            key={this.state.addModalKey}
            height={800}
            style={{overuserY:'auto',overuserX:'hidden'}}
          >
            <WrappedUserAddForm id={0} type={type} handleAddCancel={this.handleAddCancel} refresh={this.refresh1} />
          </Modal>

          <Drawer
            width={640}
            placement="right"
            closable={false}
            onClose={this.handleCollapseCancel}
            visible={this.state.collapseVisible}
          >
          <p style={{ ...pStyle, marginBottom: 24 }}>刘玉峰已分配的任务</p>

          <Collapse >
            <Panel header={<div><span style={{marginRight:'10px'}}>特惠板机型新增</span><Tag color="#f50">待完成</Tag></div>} key="1">
              <Row>
                <Col span={24}>
                  <DescriptionItem title="需求描述" content="官网页面内容刷新" />
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <DescriptionItem title="编号" content="O0003" />
                </Col>
                <Col span={12}>
                  <DescriptionItem title="语种" content="英语" />
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <DescriptionItem title="类别" content="线上内容维护（复杂）" />
                </Col>
                <Col span={12}>
                  <DescriptionItem title="交付文件" content="HTML页面" />
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <DescriptionItem title="数量" content="1" />
                </Col>
                <Col span={12}>
                  <DescriptionItem title="单位" content="套" />
                </Col>
              </Row>
              
              <Row>
              <Steps current={1}>
                <Step title="开始" description="2021-06-10 14:18:56" />
                <Step title="进行中" description="" />
                <Step title="完成" description="" />
              </Steps>
              </Row>
            </Panel>

            <Panel header={<div><span style={{marginRight:'10px'}}>特惠板机型新增</span><Tag color="#f50">待完成</Tag></div>} key="2">
              <Row>
                <Col span={24}>
                  <DescriptionItem title="需求描述" content="官网页面内容刷新" />
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <DescriptionItem title="编号" content="O0003" />
                </Col>
                <Col span={12}>
                  <DescriptionItem title="语种" content="英语" />
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <DescriptionItem title="类别" content="线上内容维护（复杂）" />
                </Col>
                <Col span={12}>
                  <DescriptionItem title="交付文件" content="HTML页面" />
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <DescriptionItem title="数量" content="1" />
                </Col>
                <Col span={12}>
                  <DescriptionItem title="单位" content="套" />
                </Col>
              </Row>
              
              <Row>
              <Steps current={1}>
                <Step title="开始" description="2021-06-10 14:18:56" />
                <Step title="进行中" description="" />
                <Step title="完成" description="" />
              </Steps>
              </Row>
            </Panel>

            <Panel header={<div><span style={{marginRight:'10px'}}>特惠板机型新增</span><Tag color="#87d068">已完成</Tag></div>} key="3">
              <Row>
                <Col span={24}>
                  <DescriptionItem title="需求描述" content="官网页面内容刷新" />
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <DescriptionItem title="编号" content="O0003" />
                </Col>
                <Col span={12}>
                  <DescriptionItem title="语种" content="英语" />
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <DescriptionItem title="类别" content="线上内容维护（复杂）" />
                </Col>
                <Col span={12}>
                  <DescriptionItem title="交付文件" content="HTML页面" />
                </Col>
              </Row>

              <Row>
                <Col span={12}>
                  <DescriptionItem title="数量" content="1" />
                </Col>
                <Col span={12}>
                  <DescriptionItem title="单位" content="套" />
                </Col>
              </Row>
              
              <Row>
              <Steps current={1}>
                <Step title="开始" description="2021-06-10 14:18:56" />
                <Step title="进行中" description="" />
                <Step title="完成" description="" />
              </Steps>
              </Row>
            </Panel>

            
            
          </Collapse>
          
        </Drawer>

        </Col>
      </Row>
    );
  }
}

export default () => (
  <div className={styles.container}>
    <div id="components-table-demo-ajax">
      <App />
    </div>
  </div>
);
